import { type AxiosPromise } from "axios";
import { get, post } from "@/utils/request";
import { useMutation, useQueryClient } from "@tanstack/react-query";

export const userKeys = {
  all: () => ["users"],
};
export interface UserQueryParams {
  [key: string]: unknown;
}

export const users = (data: UserQueryParams = {}): AxiosPromise => {
  return get("/users", data);
};

export interface UserAddData {
  [key: string]: unknown;
}

export const userAdd = (data: UserAddData): AxiosPromise => {
  return post("/users", data);
};

export interface UserDeleteData {
  [key: string]: unknown;
}

export const userDelete = (data: UserDeleteData): AxiosPromise => {
  return post("/users/delete", data);
};

export interface UserUpdateData {
  [key: string]: unknown;
}

export const userUpdate = (data: UserUpdateData): AxiosPromise => {
  return post("/users/update", data);
};

export function useUserAdd() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (newData: UserAddData) => {
      await queryClient.cancelQueries({ queryKey: userKeys.all() });
      return userAdd(newData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userKeys.all() });
    },
  });
}

export function useUserDelete() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: UserDeleteData) => {
      return userDelete(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userKeys.all() });
    },
  });
}

export function useUserUpdate() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: UserUpdateData) => {
      return userUpdate(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userKeys.all() });
    },
  });
}
